package com.far.game.xiuzhen.common.utils;



import com.far.game.xiuzhen.common.dto.TokenParam;
import com.far.game.xiuzhen.common.dto.Visitor;
import org.springframework.util.StringUtils;


import javax.servlet.http.HttpServletRequest;

/*
 * @description: TODO
 * @author mike/Fang.J/Q184377367
 * @date 2022/4/12 1:28
 */
public class RequestUtils {


    public static TokenParam getTokenParam(HttpServletRequest request) {

        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("Token不能为空!");
        }

        if (!JWTUtils.verifyTime(token, AppUtil.JWTKEY)) {
            throw new RuntimeException("Token过期");
        }
        Visitor visitor = new Visitor();
        visitor.setUserName(JWTUtils.get(token, AppUtil.JWTKEY, "userName"));
        visitor.setTid(JWTUtils.get(token, AppUtil.JWTKEY, "userTid"));

        return TokenParam.create().setVisitor(visitor);
    }

    public static TokenParam getTokenParam(String token) {

        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("Token不能为空!");
        }
        if (!JWTUtils.verifyTime(token, AppUtil.JWTKEY)) {
            throw new RuntimeException("Token过期");
        }

        Visitor visitor = new Visitor();
        visitor.setUserName(JWTUtils.get(token, AppUtil.JWTKEY, "userName"));
        Long userTid = JWTUtils.get(token, AppUtil.JWTKEY, "userTid");
      //  visitor.setTid(userTid);
        return TokenParam.create().setVisitor(visitor);
    }


    public static String getToken(HttpServletRequest request) {
        Optional<String> token = Optional.of(request.getHeader("token")).orElse(request.getHeader("X-Token"));
        return token.getVal();
    }


}
